import install.ren.exercise.test.netty.MessageDecoder;
import install.ren.exercise.test.netty.MessageEncoder;
import install.ren.exercise.test.netty.MessageHandler;
import install.ren.exercise.test.netty.TestMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author zhuyunhui 2020-07-01
 */
public class NettyClientTest2 {
    private static int maxFrameLength = 2048000;

    public static void main(String[] args) throws InterruptedException {

        String host = "";
        int port = 8800;
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    //pipeline.addLast(new Socks4ProxyHandler(new InetSocketAddress(proxyIp, port)));
                    //inbound decoder
                    pipeline.addLast("decoder", new MessageDecoder(maxFrameLength));
                    //outbound encoder
                    pipeline.addLast("encoder", new MessageEncoder());
                    MessageHandler messageHandler = new MessageHandler();
                    pipeline.addLast("hanlder", messageHandler);
                }
            });

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync(); // (5)

            f.channel().writeAndFlush(new TestMessage());
            System.out.println("=");
            f.channel().writeAndFlush(new TestMessage());
            System.out.println("=");
            f.channel().writeAndFlush(new TestMessage());
            System.out.println("=");
            f.channel().writeAndFlush(new TestMessage());
            System.out.println("=");
            f.channel().writeAndFlush(new TestMessage());
            System.out.println("=");
            f.channel().writeAndFlush(new TestMessage());

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }

    }
}
